<?php
/**
 * 登录
 *
 * @author Dracowyn
 * @since 2023-11-15 12:25
 */

// 引入配置文件
include_once('config/config.php');

session_start();
$loginAuth = isset($_COOKIE['loginAuth']) ? json_decode($_COOKIE['loginAuth']) : [];

if ($loginAuth) {
	$id = $loginAuth['id'] ?? 0;
	$username = $loginAuth['username'] ?? '';

	$sql = "SELECT id, username, password, avatar, salt FROM pre_admin WHERE id = $id AND username = '$username'";

	$admin = find($sql);

	if (!$admin) {
		setcookie('loginAuth', '', time() - 1);
		showMsg('非法登录', 'login.php');
	} else {
		showMsg('已登录', 'index.php');
	}
}

if ($_POST) {
	$username = trim($_POST['username']);
	$password = trim($_POST['password']);
	$code = trim($_POST['code']) ?? '';

	if (empty($username)) {
		showMsg('用户名不能为空');
		exit();
	}

	if (empty($password)) {
		showMsg('密码不能为空');
		exit();
	}

	if (empty($code)) {
		showMsg('验证码不能为空');
		exit();
	}

	if (strtolower($code) != strtolower($_SESSION['code'])) {
		showMsg('验证码错误');
		exit();
	}

	$sql = "SELECT id, username, password, avatar, salt FROM pre_admin WHERE username = '$username'";
	$admin = find($sql);

	if (!$admin) {
		showMsg('用户名不存在');
		exit();
	}

	$password = md5($password);
	$password = md5($password . $admin['salt']);

	if ($password != $admin['password']) {
		showMsg('密码错误');
		exit();
	}

	$data = [
		'id' => $admin['id'],
		'username' => $admin['username'],
		'avatar' => $admin['avatar'],
	];

	setcookie('loginAuth', json_encode($data), time() + 3600 * 24 * 7);
	showMsg('登录成功', 'index.php');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
	<?php include_once('common/meta.php'); ?>
    <title>登录</title>
</head>
<body>

<div class="navbar">
    <div class="navbar-inner">
        <a class="brand" href="index.php"><span class="second">Admin</span></a>
    </div>
</div>

<div class="row-fluid">
    <div class="dialog">
        <div class="block">
            <p class="block-heading">登录</p>
            <div class="block-body">
                <form method="post">
                    <label>用户名</label>
                    <label>
                        <input type="text" class="span12" name="username" placeholder="请输入用户名" required>
                    </label>
                    <label>密码</label>
                    <label>
                        <input type="password" class="span12" name="password" placeholder="请输入密码" required>
                    </label>
                    <label>验证码</label>
                    <div>
                        <input type="text" name="code" class="span9" placeholder="请输入验证码" required>
                        <img src="config/imgcode.php" alt=""
                             onclick="this.src = 'config/imgcode.php?id='+Math.random();">
                    </div>

                    <button class="btn btn-primary pull-right">登录</button>
                    <div class="clearfix"></div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
<?php include_once('common/script.php'); ?>
